﻿using System.Collections.Generic;
using System.Linq;
using System.Web;
using CrazyTalk.BLL;
using CrazyTalk.Common;
using CrazyTalk.Config;
using CrazyTalk.Models;
using CrazyTalk.Models.EnumList;

namespace CrazyTalk.Web.UI
{
    public class UserHttpHandler : HttpHandlerBase
    {
        public UserHttpHandler()
        {
            IsLogin();
        }
        /// <summary>
        /// 当前用户信息
        /// </summary>
        public UserInfo CurUserInfo { get; set; }
        /// <summary>
        /// 适配用户账号
        /// 此账号的操作可以等同的账号
        /// 比如子账号等同父级账号
        /// 可以在查询权限等进行等同处理
        /// 但是具体编辑人,日志记录不可以使用等同.
        /// </summary>
        public string AdaptUserId { get; set; }
        public int AdaptRoleId { get; set; }

        /// <summary>
        /// 判断用户是否已登陆
        /// </summary>
        /// <returns></returns>
        protected bool IsLogin()
        {
            HttpCookie cookie = CurContext.Request.Cookies["CrazyTalk_tg"];
            //取出唯一识别码
            //根据唯一识别码,获取用户信息集
            if (cookie == null || cookie["_ug"] == null)
                return false;
            string userId = cookie["_ug"];
            //登陆时生成一个唯一编号guid，并记录在数据库（缓存）
            //可以再加多一些key，增加破解难度
            if (VistorUtils.VerifySign(string.Format("{0}tx{1}", userId, SecurityConfig.GetConfig().PasswordKey), cookie["Sign"]))
            {
                //获取用户信息
                UserInfoBLL bll = UserInfoBLL.Instance;
                UserInfo userInfo = bll.GetModelByCache(userId);
                if (userInfo == null)
                    return false;
                CurUserInfo = userInfo;
                if (bll.IsChildAccount2(CurUserInfo.RoleId))
                {
                    AdaptUserId = CurUserInfo.ParentId;
                    UserInfoBLL ubll = new UserInfoBLL();
                    AdaptRoleId = ubll.GetModel(CurUserInfo.ParentId).RoleId;
                }
                else
                {
                    AdaptUserId = CurUserInfo.UserId;
                    AdaptRoleId = CurUserInfo.RoleId;
                }
                return true;
            }
            return false;
        }
        public bool HasPermission()
        {
            var list = PermissionBLL.Instance.GetPermissionListByCache(CurUserInfo.UserId, CurUserInfo.RoleId);

            return (from c in list where c.MenuID == MenuId select c).Any(); ;
        }
        public bool IsAdmin
        {
            get{return CurUserInfo.RoleId == (int)ENums.ERole.Root;}
        }
        private List<Permission> _currUserPermissionList;
        /// <summary>
        /// 当前用户的权限列表
        /// </summary>
        public List<Permission> CurrUserPermissionList
        {
            get { return _currUserPermissionList ?? 
                (_currUserPermissionList = PermissionBLL.Instance.GetPermissionListByCache(CurUserInfo.UserId, CurUserInfo.RoleId)); }
            set { _currUserPermissionList = value; }

        }
        /// <summary>
        /// 判断用户是否拥有执行此程序的权限，如果没有则终止请求
        /// 由于基类执行构造函数阶段，还没有获取到继承类的MenuId的值，所以此判断方法需要手动执行。
        /// </summary>
        public void InHasPermission()
        {
            //管理员有全部的权限
            if (IsAdmin)
                return;

            if (MenuId == -1)
                return;
            if (CurrUserPermissionList == null || !(CurrUserPermissionList.Any(o => o.MenuID == MenuId)))
            {
                WriteEnd(Consts.sys_nopermiss, ENums.EErrorCode.UnPermiss);
            }            
        }

        public void WriteEnd(string msg, ENums.EErrorCode errcode)
        {
            HttpContext.Current.Response.Write(string.Format("{0}！Code={1}", msg, (int)errcode));
            HttpContext.Current.Response.End();
        }
        public int MenuId { get; set; }
        protected virtual void CheckPermit()
        {

        }      
    }
}
